﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Peppers;
using System.Peppers.ShellExtensions;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.IO;
using System.Peppers.UI;

namespace Md5ShellExtension
{
    [Guid(Constants.Guid), ComVisible(true), 
        ShellExtension(Name = Constants.DisplayName, Data = new string[] { FileExtension.AllFiles })]
    public class Md5ContextMenu : ContextMenuBase
    {
        private static MD5CryptoServiceProvider _md5 = new MD5CryptoServiceProvider();

        public Md5ContextMenu()
        {
            MessageBox.Show("MD5 is here!");

            ContextMenuQueried += new EventHandler(ShellExtension_ContextMenuQueried);
        }

        private void ShellExtension_ContextMenuQueried(object sender, EventArgs e)
        {
            //Only on one file
            if (Files.Count == 1)
            {
                ContextMenuItem item = new ContextMenuItem();
                item.Text = "Calculate &MD5 Hash";
                item.Click += (EventHandler)
                    delegate
                    {
                        byte[] hash = _md5.ComputeHash(File.ReadAllBytes(Files[0]));
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < hash.Length - 1; i += 2)
                        {
                            string hex = hash[i].ToString("x");
                            if (hex.Length == 1)
                            {
                                builder.Append('0');
                            }
                            builder.Append(hex);
                        }
                        MessageBox.Show(builder.ToString(), "MD5 Hash");
                    };
                Items.Add(item);
            }
        }

        #region COM Registration
        [ComRegisterFunction]
        private static void RegisterServer(string zRegKey)
        {
            RegisterExtension(typeof(Md5ContextMenu));
        }

        [ComUnregisterFunction]
        private static void UnregisterServer(string zRegKey)
        {
            UnregisterExtension(typeof(Md5ContextMenu));
        }
        #endregion
    }
}
